
import { observable, action, computed, reaction,autorun,makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';
import {useState} from 'react';
class TodoStore{
    todos = [//定义类的实例属性todos
        {id:1,text:'redux',completed:true},
        {id:2,text:'mobx',completed:false},
    ]
    constructor(){
        //把当前的类的实例标记为自动的可观察对象
        //如果这样调用了以后属性就是变成可观察变量了
        //方法就自动可以修改变量的action了
        makeAutoObservable(this);
    }
    toggle(id){
        const todo = this.todos.find(todo=>todo.id === id);
        if(todo)todo.completed= !todo.completed;
    }
    addTodo(text){
        this.todos.push({text,id:this.todos.length+1,completed:false});
    }
    get completedTodosCount(){//已完成的todo的数量
        return this.todos.filter(todo=>todo.completed).length;
    }
}
const store = new TodoStore();
function MobxApp(){
    const [text,setText] = useState('');
    const addTodo = ()=>{
        store.addTodo(text);
        setText('');
    }
    return (
        <div>
            <input value={text} onChange={event=>setText(event.target.value)}/>
            <button onClick={addTodo}>增加</button>
            <ul>
                {
                    store.todos.map(todo=>(
                        <li key={todo.id}>
                            <input 
                            type='checkbox' 
                            checked={todo.completed} 
                            onChange={()=>store.toggle(todo.id)}/>
                            {todo.text}
                            </li>
                    ))
                }
            </ul>
            <p>已完成的数量{store.completedTodosCount}</p>
        </div>
    );
}
export default observer(MobxApp);